package com.weixin.pay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.talkology.pilot.database.dao.UserMapper;
import com.talkology.pilot.database.model.AccessToken;
import com.talkology.pilot.database.model.User;
import com.weixin.pay.service.IAccessTokenService;
import com.weixin.pay.util.WXUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信用户授权控制类
 *
 * @author longJp
 * @date 2018/7/30
 */
@RestController
@RequestMapping("/weixin/auth")
public class WXAuthController {
    private static final Logger log = LoggerFactory.getLogger(WXAuthController.class);

    @Resource
    private WXUtils wxUtils;

    @Autowired
    private IAccessTokenService service;

    @Autowired
    private UserMapper mapper;

    /**
     * 微信网页授权
     * https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
     * 第一步：用户同意授权，获取code
     * 第二步：通过code换取网页授权access_token
     * @return str
     *
     * @author longJp
     * @date 2018/7/30
     */
    @ApiOperation(value = "网页授权，获得个人的access_token", httpMethod = "GET", notes = "获取前端微信用户的网页授权，得到用户对应个个人access_token和openid")
    @GetMapping("/authorize/{code}/{state}")
    @ResponseBody
    public JSONObject authorize(@PathVariable String code, @PathVariable String state) throws Exception {
        log.info("authorize:code:{}", code);
        // 获取access_token和openid
        JSONObject jsonToken = wxUtils.getJsapiAccessTokenByCode(code);
        if (null == jsonToken) {
            throw new RuntimeException("Cannot pass certification. ");
        }
        return jsonToken;
    }


    @ApiOperation(value = "获取全局的access_token", httpMethod = "GET", notes = "获取全局的access_token，后台一个半小时会自动刷新一次")
    @RequestMapping(value = "/recentToken", method= RequestMethod.GET)
    @ResponseBody
    public String getAccessToken() {
        return service.getInfo(0).getToken();
    }



    @ApiOperation(value = "手动刷新全局的access_token", httpMethod = "GET")
    @RequestMapping(value = "/refreshToken", method= RequestMethod.POST)
    @ResponseBody
    public String refreshAccessToken() {
        AccessToken record = new AccessToken();
        String newToken = wxUtils.getNewToken();
        record.setToken(newToken);
        record.setIndex(0);
        record.setUpdatedAt(new Date());
        service.edit(record);
        return newToken;
    }

    /**
     * 通过access_token和openid请求获取用户信息(需scope为 snsapi_userinfo)
     * @return str
     *
     * @author longJp
     * @date 2018/7/31
     */
    @ApiOperation(value = "通过code请求获取用户信息", httpMethod = "POST", notes = "通过code请求获取用户信息, 其中state只是用于是否有页面跳转的判断")
    @PostMapping("/userinfo/{code}/{state}")
    @Transactional
    @ResponseBody
    public JSONObject userinfo(@PathVariable String code, @PathVariable String state) {
        JSONObject jsonToken = wxUtils.getJsapiAccessTokenByCode(code);
        if (null == jsonToken) {
            throw new RuntimeException("Cannot pass certification. ");
        }
        String access_token = jsonToken.getString("access_token");
        String openid = jsonToken.getString("openid");
        // 通过access_token和openid请求获取用户信息
        JSONObject jsonUserinfo = wxUtils.getJsapiUserinfo(access_token, openid);
        if (null == jsonUserinfo) {
            throw new RuntimeException("Can't get wx user info.");
        }

        // 判断用户是否在系统中是一个用户
        String unionid = jsonUserinfo.getString("unionid");
        if (StringUtils.isBlank(unionid)) {
            throw new RuntimeException("unionid is null.");
        }


        // 存储用户信息到数据库
        User user = mapper.queryByOpenid(openid);
        if (user == null) {
            user = JSON.parseObject(jsonUserinfo.toJSONString(), User.class);
            user.setCreatedAt(new Date());
            // 处理微信昵称emoji表情
//            if (StringUtils.isNotBlank(user.getNickname())) {
                // 编码Base64.decodeBase64()
//                user.setNickname(UserNickUtil.encodeNickName(user.getNickName()));
//            }
//            userService.createEntity(user);
            mapper.insert(user);
        }
        // 用户名称解码
//        user.setNickName(UserNickUtil.decodeNickName(user.getNickName()));
//        UserAccount userAccount = userAccountService.queryByUserId(user.getId());
//        map.put("user", user);

        return jsonUserinfo;
    }

}
